#include "MQTTClientMain.h"
#include "ui_MQTTClientMain.h"
#include "NewConnect.h"
#include "ConnectManager.h"
#include "DataCtrl.h"
#include <QDebug>
#include <QThread>
#include <QMetaType>
#include <QSettings>

CMQTTClientMain::CMQTTClientMain(QWidget *parnet /*= nullptr*/)
	: QWidget(parnet)
	, m_ui(new Ui::MQTTClientMain)
	, m_pDataCtrl(nullptr)
	, m_pCtrlThread(nullptr)
{
	m_ui->setupUi(this);
	init();
}

CMQTTClientMain::~CMQTTClientMain()
{
	if (m_pCtrlThread)
	{
		m_pCtrlThread->quit();
		m_pCtrlThread->exit();
		m_pCtrlThread->wait();
		delete m_pCtrlThread;
		m_pCtrlThread = nullptr;
	}
	if (m_pDataCtrl)
	{
		delete m_pDataCtrl;
		m_pDataCtrl = nullptr;
	}
	delete m_ui;
}

void CMQTTClientMain::init()
{
	qRegisterMetaType<CConnectOpt>("CConnectOpt");
	m_pDataCtrl = new CDataCtrl;
	m_pCtrlThread = new QThread(this);

	if (m_pCtrlThread && m_pDataCtrl)
	{
		m_pDataCtrl->moveToThread(m_pCtrlThread);
	}
	connect(this, SIGNAL(sigInitDbData()), m_pDataCtrl, SLOT(slotInitDbData()));
	emit sigInitDbData();
	m_pCtrlThread->start();
	QSettings st(QString("Liu"), QString("MQTTClient"));
	int status = st.value(QString("OpenConnectManager")).toInt();
	if (status == 2)
	{
		on_btnOpenConnect_clicked();
	}
}

void CMQTTClientMain::on_btnNewConnect_clicked()
{
	CNewConnect dlg(m_pDataCtrl, this);
	connect(&dlg, SIGNAL(sigInsertConnect(QString, CConnectOpt)), m_pDataCtrl, SLOT(slotInsertConnect(QString, CConnectOpt)));
	dlg.exec();
}

void CMQTTClientMain::on_btnOpenConnect_clicked()
{
	CConnectManager dlg(m_pDataCtrl, this);
	connect(&dlg, SIGNAL(sigInsertGroup(QString, QString)), m_pDataCtrl, SLOT(slotInsertGroup(QString, QString)));
	connect(&dlg, SIGNAL(sigDeleteGroup(QString)), m_pDataCtrl, SLOT(slotDeleteGroup(QString)));
	connect(&dlg, SIGNAL(sigUpdateGroup(QString, QString)), m_pDataCtrl, SLOT(slotUpdateGroup(QString, QString)));
	dlg.exec();
}

